package com.ihrm.system.controller;


import com.github.pagehelper.PageInfo;
import com.ihrm.common.controller.BaseController;
import com.ihrm.common.entity.Result;
import com.ihrm.common.entity.ResultCode;
import com.ihrm.domain.system.response.RoleResult;
import com.ihrm.domain.system.Role;
import com.ihrm.system.service.api.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author chentao
 */
@CrossOrigin
@RestController
@RequestMapping(value = "/system")
public class RoleController extends BaseController {
    @Autowired
    private RoleService roleService;

    /**
     * 添加角色
     */
    @RequestMapping(value = "/role", method = RequestMethod.POST)
    public Result save(@RequestBody Role role) {
        //设置保存的企业id及名字
        role.setCompanyId(companyId);
        roleService.add(role);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 更新角色
     */
    @RequestMapping(value = "/role", method = RequestMethod.PUT)
    public Result update(@RequestBody Role role) {
        //完成更新
        roleService.update(role);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 根据id删除角色
     */
    @RequestMapping(value = "/role/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable(value = "id") String id) {
        roleService.deleteById(id);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 根据id查询单个角色
     */
    @RequestMapping(value = "/role/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable(value = "id") String id) {
        Role role = roleService.findById(id);
        RoleResult roleResult = new RoleResult(role);
        return new Result(ResultCode.SUCCESS, roleResult);
    }

    /**
     * 分页查询角色列表
     */
    @RequestMapping(value = "/role", method = RequestMethod.GET)
    public Result findByPage(int page, int size) {
        PageInfo<Role> roleListPageInfo = roleService.getRoleListPageInfo(companyId, page, size);
        return new Result(ResultCode.SUCCESS, roleListPageInfo);
    }


    /**
     * 查询角色列表
     */
    @RequestMapping(value = "/role/list", method = RequestMethod.GET)
    public Result findAll() {
        List<Role> all = roleService.findAll();
        return new Result(ResultCode.SUCCESS, all);
    }

    /**
     * 分配权限
     */
    @RequestMapping(value = "/role/assignPrem", method = RequestMethod.PUT)
    public Result assignPrem(@RequestBody Map<String, Object> map) {
        //获取被分配权限的角色id
        String roleId = (String) map.get("id");
        //获取权限的id列表
        List<String> permIds = (List<String>) map.get("permIds");
        roleService.assignPerms(roleId, permIds);
        return new Result(ResultCode.SUCCESS);
    }

}
